#include "rolemgmt.h"
#include "ui_rolemgmt.h"

#include <QDebug>
#include "roletoolbox.h"
#include "roleconfigdialog.h"
#include "roleaccessdialog.h"
#include "mainwindow.h"

RoleMgmt::RoleMgmt(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RoleMgmt)
{
    ui->setupUi(this);
    ui->tableWidget->setColumnHidden(0, true);  //隐藏id列

    int widths[] = {0, 100, 400, 0, 200, 400, 100};
    for(int i=1; i<=6; i++)
        ui->tableWidget->setColumnWidth(i, widths[i]);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Stretch);
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);

    switchToPage(1);
}

RoleMgmt::~RoleMgmt()
{
    delete ui;
}

bool RoleMgmt::refresh(QSqlQuery query)
{
    if(query.size() <= 0){
        ui->tableWidget->setRowCount(0);
        return false;
    }

    ui->tableWidget->setRowCount(query.size());
    for(int i=0; i<query.size(); i++){
        if(query.next()){
            for(int j=3; j<=5; j++){
                ui->tableWidget->setItem(i,j,new QTableWidgetItem(query.value(j-2).toString()));
            }
            ui->tableWidget->setItem(i,0,new QTableWidgetItem(query.value(0).toString()));//记录id, 隐藏列
            ui->tableWidget->setItem(i,1,new QTableWidgetItem(QString("%1").arg((nowPage-1)*pageLineNum+i+1)));//序号
            ui->tableWidget->setCellWidget(i,2, new RoleToolBox(this));//操作栏
            ui->tableWidget->setItem(i,6,new QTableWidgetItem(query.value(4).toInt() == 1 ? "启用" : "禁用"));
            ui->tableWidget->item(i,1)->setCheckState(Qt::Unchecked);
            //全部居中
            for(int j=1; j<=6; j++){
                if(ui->tableWidget->item(i,j) == nullptr) continue;
                ui->tableWidget->item(i,j)->setTextAlignment(Qt::AlignCenter);
            }
        }else{
            break;
        }
    }
    return true;
}

int RoleMgmt::getBtnRow(QPushButton* btn)
{
//    QPushButton *btn = (QPushButton*) sender();
    int x = btn->parentWidget()->frameGeometry().x();
    int y = btn->parentWidget()->frameGeometry().y();
    QModelIndex index = ui->tableWidget->indexAt(QPoint(x, y));
//    return ui->tableWidget->item(index.row(), 0)->text();
    return index.row();
}

//功能按钮
void RoleMgmt::btn_func_clicked()
{
    int row = getBtnRow((QPushButton*) sender());
    int id = ui->tableWidget->item(getBtnRow((QPushButton*) sender()), 0)->text().toInt();
    QString name = ui->tableWidget->item(row, 3)->text();
    RoleAccessDialog * access = new RoleAccessDialog(this, id, name);
    access->show();
}
void RoleMgmt::btn_edit_clicked()
{
    int id = ui->tableWidget->item(getBtnRow((QPushButton*) sender()), 0)->text().toInt();
    RoleConfigDialog *conf = new RoleConfigDialog(this, id);
    conf->show();
}
void RoleMgmt::btn_del_clicked()
{
    int row = getBtnRow((QPushButton*) sender());
    QString tip = QString("确实要删除角色\"%1\"吗?").arg(ui->tableWidget->item(row, 3)->text());
    if(QMessageBox::No == QMessageBox::question(this, "提示", tip, QMessageBox::Yes|QMessageBox::No)) return;

    int id = ui->tableWidget->item(row, 0)->text().toInt();
    QString sql = QString("UPDATE dm_role SET delete_flag='1' WHERE id='%1'").arg(id);
    QSqlQuery query;
    if(query.exec(sql)){
        mydb->addLog(DM_Window->current_user_id, "角色管理", QString("删除角色\\'%1\\'").arg(ui->tableWidget->item(row, 3)->text()), "1");
    }
    updatePage();
}

//增加和批量操作
void RoleMgmt::on_btn_add_clicked()
{
    RoleConfigDialog *conf = new RoleConfigDialog(this, -1);
    conf->show();
}
void RoleMgmt::on_btn_batch_del_clicked() //批量删除
{
    QList<int> list;
    for(int i=0; i<ui->tableWidget->rowCount(); i++){
        if(ui->tableWidget->item(i,1)->checkState()){
            list.append(i);
        }
    }
    if(list.size() <= 0){
        QMessageBox::information(this, "提示", "没有选择角色");
        return;
    }
    if(QMessageBox::No == QMessageBox::question(this, "提示",
        QString("确定要删除%1个角色吗？").arg(list.size()), QMessageBox::Yes|QMessageBox::No)) return;

    QSqlQuery query;
    QString log = QString("删除%1个角色:").arg(list.size());
    QString where = " WHERE";
    for(int i=0; i<list.size(); i++){   //list[i]
        log += QString("<%1>").arg(ui->tableWidget->item(list[i],3)->text());
        where += QString(" OR id='%1'").arg(ui->tableWidget->item(list[i],0)->text().toInt());
    }
    where.replace(" WHERE OR", " WHERE");
    qDebug() << "UPDATE dm_role SET delete_flag=1" + where;
    if(query.exec("UPDATE dm_role SET delete_flag=1" + where))
        mydb->addLog(DM_Window->current_user_id, "角色管理", log, "1");

    updatePage();
}

//更新当前页和翻页部分
void RoleMgmt::updatePage(){switchToPage(nowPage);}
void RoleMgmt::on_btn_page_minus_clicked(){switchToPage(nowPage-1);}
void RoleMgmt::on_btn_page_plus_clicked(){switchToPage(nowPage+1);}
void RoleMgmt::on_btn_page_head_clicked(){switchToPage(1);}
void RoleMgmt::on_btn_page_end_clicked(){switchToPage(999999999);}

void RoleMgmt::switchToPage(int page)
{
    QSqlQuery query = mydb->query("dm_role", "COUNT(*)", keyword);
    if(!query.next()) return;

    totalLineNum = query.value(0).toInt();
    totalPage = (int)ceil((float) totalLineNum/pageLineNum);
    ui->lb_totolpage->setText(QString("/%1").arg(totalPage));
    if(page > totalPage) page = totalPage;
    if(page < 1) page = 1;
    ui->le_nowpage->setText(QString("%1").arg(page));
    nowPage = page;

    QString limit = QString(" LIMIT %1,%2").arg((page-1)*pageLineNum).arg(pageLineNum);
    query = mydb->query("dm_role", "id,name,type,description,enabled", keyword, order, limit);
    refresh(query);
}

//查询和重置
void RoleMgmt::on_btn_reset_clicked()
{
    keyword = defalut_keyword;
    switchToPage(1);
}
void RoleMgmt::on_btn_search_clicked()
{
    keyword = defalut_keyword;
    if(!ui->le_name->text().isEmpty()){
        keyword += QString(" AND name LIKE '%%1%'").arg(ui->le_name->text());
    }
    if(!ui->le_remark->text().isEmpty()){
        keyword += QString(" AND description LIKE '%%1%'").arg(ui->le_remark->text());
    }
    switchToPage(1);
}
